package br.com.werp.regras.acesso.visao.taglib;

import br.com.werp.regras.acesso.controle.ControleAcesso;
import br.com.werp.regras.geral.GerenciadorErros;
import br.com.werp.regras.geral.visao.taglib.MasterTag;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class AcessoTag extends MasterTag {
    private static final long serialVersionUID = -1088653082387063806L;
    private static final String PAG_NEGADO = "/negado.jsp";
    private static final String PAG_LOGIN = "/LoginForm.jsp";
    private ControleAcesso controleAcesso = new ControleAcesso();

    public void otherDoStartTagOperations() {
        HttpServletRequest request =
            (HttpServletRequest) pageContext.getRequest();

        try {
            String usuario =
                (String) pageContext.getSession().getAttribute("j_username");
            String uri = request.getRequestURI();

            if (usuario == null) {
                HttpServletResponse response =
                    (HttpServletResponse) pageContext.getResponse();
                response.sendRedirect(request.getContextPath() + PAG_LOGIN);
            } else if (uri.endsWith("Banner.jsp") || uri.endsWith("index.jsp")) {
                return;
            } else if (!controleAcesso.verificaUsuarioAcessoUrl(usuario, uri)) {
                dispachaNegado(request, PAG_NEGADO);
            }
        } catch (Exception e) {
            GerenciadorErros.logarErro(e);
        }
    }

    private void dispachaNegado(HttpServletRequest request, String page)
        throws ServletException,IOException {
        pageContext.getRequest().setAttribute("negado", request.getRequestURI());

        RequestDispatcher dispatcher =
            pageContext.getServletContext().getRequestDispatcher(page);
        dispatcher.forward(pageContext.getRequest(), pageContext.getResponse());
    }
}
